#!/bin/bash


# 输出可用的物理网卡列表供选择
echo "当前系统中的物理网卡："
PHYSICAL_NICS=$(ls /sys/class/net | grep -v -e 'lo' -e 'bond' -e 'br' -e 'docker' -e 'veth')
select NIC in $PHYSICAL_NICS; do
    if [[ -n "$NIC" ]]; then
        echo "已选择物理网卡：$NIC"
        break
    else
        echo "无效选择，请重新选择。"
    fi
done

# 选择绑定模式
echo "请选择绑定模式（默认为 mode 1: active-backup）："
echo "1) active-backup"
echo "2) balance-rr"
echo "3) balance-xor"
echo "4) broadcast"
echo "5) 802.3ad"
echo "6) balance-tlb"
echo "7) balance-alb"
read -p "请输入绑定模式编号（默认1）：" MODE
MODE=${MODE:-1}

case $MODE in
    1) BOND_MODE="active-backup" ;;
    2) BOND_MODE="balance-rr" ;;
    3) BOND_MODE="balance-xor" ;;
    4) BOND_MODE="broadcast" ;;
    5) BOND_MODE="802.3ad" ;;
    6) BOND_MODE="balance-tlb" ;;
    7) BOND_MODE="balance-alb" ;;
    *) echo "无效模式编号，默认使用 active-backup" ; BOND_MODE="active-backup" ;;
esac
echo "已选择绑定模式：$BOND_MODE"

# 选择网络配置方式
echo "选择网络配置方式："
echo "1) 手动输入IP地址等信息"
echo "2) 重用选定网卡($NIC)的现有配置"
read -p "请输入选项编号（默认1）：" CONFIG_OPTION
CONFIG_OPTION=${CONFIG_OPTION:-1}

if [[ "$CONFIG_OPTION" -eq 1 ]]; then
    read -p "请输入 IP 地址：" IP_ADDR
    read -p "请输入子网掩码：" NETMASK
    read -p "请输入网关：" GATEWAY
    read -p "请输入 DNS 服务器：" DNS
else
    IP_ADDR=$(ip -4 addr show $NIC | grep -oP '(?<=inet\s)\d+(\.\d+){3}')
    NETMASK=$(ip -4 addr show $NIC | grep -oP '(?<=/)\d+')
    GATEWAY=$(ip route | grep default | grep $NIC | awk '{print $3}')
    DNS=$(cat /etc/resolv.conf | grep -i '^nameserver' | awk '{print $2}' | head -n1)
    echo "重用现有配置：IP=$IP_ADDR, NETMASK=$NETMASK, GATEWAY=$GATEWAY, DNS=$DNS"
fi

# 设置备份目录
BACKUP_DIR="/etc/sysconfig/network-scripts/backup_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"
echo "网络配置文件将备份到目录：$BACKUP_DIR"

# 备份现有的 NetworkManager 配置
mv  /etc/sysconfig/network-scripts/ifcfg-${NIC} "$BACKUP_DIR/"
mv  /etc/sysconfig/network-scripts/ifcfg-mgmt-bo "$BACKUP_DIR/"
mv  /etc/sysconfig/network-scripts/ifcfg-mgmt-br "$BACKUP_DIR/"
echo "已备份 NetworkManager 配置文件到 $BACKUP_DIR"

# 使用 nmcli 创建 mgmt-bo 绑定接口
nmcli connection add type bond con-name mgmt-bo ifname mgmt-bo mode $BOND_MODE
#nmcli connection modify mgmt-bo ipv4.addresses $IP_ADDR/$NETMASK ipv4.gateway $GATEWAY ipv4.dns $DNS ipv4.method manual
nmcli connection add type ethernet slave-type  bond con-name $NIC ifname $NIC master mgmt-bo
echo "已创建 mgmt-bo 绑定接口，并将 $NIC 作为其从属设备"

# 使用 nmcli 创建 mgmt-br 网桥
nmcli connection add type bridge con-name mgmt-br ifname mgmt-br ipv4.addresses $IP_ADDR/$NETMASK ipv4.gateway $GATEWAY ipv4.dns $DNS ipv4.method manual
nmcli connection modify mgmt-br bridge.stp no
nmcli connection modify mgmt-bo master mgmt-br
echo "已创建 mgmt-br 网桥，并将 mgmt-bo 绑定接口添加到网桥"

nmcli con reload

# 启用新的网络配置
nmcli connection up mgmt-bo
nmcli connection up mgmt-br
echo "新的网络配置已启用，正在显示 mgmt-br 网桥的配置信息："
sleep 5
nmcli device show mgmt-br

